package com.swsm.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.alibaba.fastjson.JSONObject;
import com.swsm.exception.ParseXmlException;
import com.swsm.model.UserModel;

public class UserParse {
	
	public static List<UserModel> xlsParse(String filePath, int sheet) {
		List<UserModel> list = new ArrayList<>();
		try {
			FileInputStream fis = new FileInputStream(new File(filePath));
			HSSFWorkbook workbook = new HSSFWorkbook(fis);
			HSSFSheet childSheet = workbook.getSheetAt(sheet);
			
			int lastRowNum = childSheet.getLastRowNum();
			int lastCellNum = childSheet.getRow(0).getLastCellNum();
			
			HSSFRow row = null;
			HSSFCell cell = null;
			
			for (int i = 1; i < lastRowNum; i++) {
				row = childSheet.getRow(i);
				if (row.getCell(3) == null) {
					break;
				}
				Integer userNo = Integer.parseInt(getValue(row.getCell(3)));
				UserModel model = new UserModel();
				model.setNo(userNo);
				model.setName(getValue(row.getCell(4)).trim());
				model.setSex(getValue(row.getCell(6)).trim());
				model.setGrade(Integer.parseInt(getValue(row.getCell(7))));
				model.setClazz(getValue(row.getCell(lastCellNum-5)).trim().substring(5));
				model.setPassword(PinYinUtils.getFirstSpell(model.getName())+userNo);
				list.add(model);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			throw new ParseXmlException("文件解析错误，请选择正确文件");
		}
		return list;
	}
	
	private static String getValue(HSSFCell cell) {
		try {
			return cell.getStringCellValue();
		} catch (Exception e) {
		}
		try {
			return String.valueOf((int)cell.getNumericCellValue());
		} catch (Exception e) {
		}
		try {
			return String.valueOf(cell.getBooleanCellValue());
		} catch (Exception e) {
		}
		return null;
	}
}
